<!-- 
语音通话（群聊可拖转）
`call_status` int(11) DEFAULT '0' COMMENT '通话状态 0空闲  1呼叫中 2通话中',
 -->
<template>
	<div>
		<audio ref="audioplay" :src="apifun.hrefURL+'/static/14060.mp3'"></audio>
		<div class="topcontrol curpoin">
			<div class="topcontrolr flex">
				<!-- <p class="topcontrolreach curpoin" @click="mini">
					<span class="curpoin el-icon-minus"></span>
				</p> -->
				<p class="topcontrolreach curpoin" @click="colsed">
					<span class="curpoin el-icon-close"></span>
				</p>
			</div>
		</div>
		<div class="voicemain">
			<div class="voicemain-head">
				<div class="voicemain-headavater" v-if="groupUserData.length <= 0">
					<div class="headavatereach">
						<img v-if="youMsg.avatar" :src="apifun.URLimg + youMsg.avatar" alt="头像" />
						<img v-if="!youMsg.avatar" src="@/assets/logosvg.png" alt="头像" />
						<p class="headavatereachtitle ellipsis01">{{ youMsg.realname }}</p>
					</div>
				</div>
				<div class="voicemain-headavater" v-if="groupUserData.length > 0">
					<div class="headavatereach" v-for="(item,index) in groupUserData" :key="index">
						<img v-if="item.avatar" :src="apifun.URLimg + item.avatar" alt="头像" />
						<img v-if="!item.avatar" src="@/assets/logosvg.png" alt="头像" />
						<p class="headavatereachtitle ellipsis01">{{ item.realname }}</p>
					</div>
				</div>
				<div class="voicemain-headname" v-if="state == 1">正在等待对方接听</div>
				<div class="voicemain-headname" v-if="state == 2">邀请你语音通话</div>
				<div class="voicemain-headname" v-if="state == 3">通话中...</div>
				<div class="voicemain-headname" v-if="state == 4">通话结束</div>
			</div>
			<div class="voicemain-bottonbtn">
				<div class="voicemain-btnequipment" v-if="!iszcTRTC">当前设备浏览器不支持音频功能，请检查设备或转至手机继续语音</div>
				<div class="voicemain-btnequipment" v-if="microphonenum <= 0">未检测到麦克风，请检查设备或转至手机继续语音</div>
				<div class="voicemain-bottonbtnmain marginAuto flex" v-if="btnshow">
					<div class="voicemain-bottonbtneach flex">
						<img style="width:50px;height:50px" @click="exitRoomfun" src="@/assets/chat/stopvoice.png"
							alt="挂断" />
					</div>
					<div class="voicemain-bottonbtneach flex" v-if="state == 2">
						<img style="width:50px;height:50px" @click="sendcalljtfun" src="@/assets/chat/startvoice.png"
							alt="接听" />
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { ipcRenderer } from "electron";
	import TRTC from 'trtc-sdk-v5';
	import utils from '@/utils/utils';
	import RTCDetect from 'rtc-detect';
	export default {
		data() {
			return {
				infodataacitem: {},  // 拨打时对方数据
				statustype:1,  // 1拨打2接听
				answer: {}  ,// 推送数据
				
				state: 1, // 1正在等待对方接听 2邀请你语音 3通话中4结束
				sdkAppId: 1600046845,
				secretKey: '3c521e02d23c3b687a11bf15daa627dd3f642e89e7d07a9b4cdfd86450cae9f0',
				userInfo: {},
				userId: '',
				youID: '',
				youMsg: {},
				msgid:'',
				chat_sign:'',
				userSig: '',
				id: '', //  消息id
				order_id:'',
				groupUserData:[],
				
				iszcTRTC: false, // 检测是否支持TRTC
				microphonenum: 0,
				microphoneId: String,
				client: null,
				btnshow:false,
				isdevice:false
			};
		},
		mounted() {
			this.isdevice = localStorage.getItem('isdevice');
			this.isdevicefun();  // 检测设备
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			this.userId = this.userInfo.user_id.toString();
			this.isSupported(); // 检测浏览器是否支持TRTC
			this.getMicrophoneList(); //  获取麦克风设备列表
			this.$refs.audioplay.play();
			ipcRenderer.on("appendMessagedata", (event, newValue) => { // 推送数据
				let answer = newValue.data;
				this.answer = answer;
				this.order_id = answer.order_id;
				this.answerfun(answer);
			});
			ipcRenderer.on("statustypedata", (event, newValue) => { // 1拨打 2 接听
			    this.statustype = newValue;
				this.state = newValue;
			});
			ipcRenderer.on("infodataacitemdata", (event, newValue) => {  // 拨打带过来
			    this.infodataacitem = newValue;
				this.order_id = newValue.order_id;
			});
			setTimeout(()=>{   // 等待接收数据
				// console.log('拨打信息infodataacitem--',this.infodataacitem);
				// console.log('1拨打2接听3中途进入',this.statustype);
				// console.log('接听信息answer--',this.answer);
				if (this.statustype == 1) { // 拨打
					this.youMsg = {
						avatar: this.infodataacitem.avatar,
						mobile: this.infodataacitem.account,
						realname: this.infodataacitem.title,
						user_id: this.infodataacitem.user_id,
					};
					this.youID = this.infodataacitem.user_id;
					this.id = utils.getUuid();
					this.btnshow = true;
					this.chat_sign = this.infodataacitem.chat_sign;
					this.callfun();  // 获取msg_id->this.initClient()->进入房间（this.enterRoomfun）
				} else if(this.statustype == 2){ // 接听
					this.state = 2;
					this.youMsg = {
						avatar: this.answer.from_user.avatar,
						realname: this.answer.from_user.realname,
						user_id: this.answer.from_user.user_id,
					};
					this.youID = this.answer.from_user.user_id;
					this.id = this.answer.id || 0;
					this.msgid = this.answer.msg_id;
					this.chat_sign = this.answer.chat_sign;
					this.btnshow = true;
					this.initClient();  // 初始化房间-进入房间、监听事件
					this.getVideoGroupUserfun();  // 获取当前房间人物信息
				}else if(this.statustype == 3){  // 中途进入房间
					this.state = 3;
					this.msgid = this.infodataacitem.msg_id;
					this.chat_sign = this.infodataacitem.chat_sign;
					this.btnshow = true;
					this.sendcalljtfun();  //接听
					this.initClient();  // 初始化房间-进入房间、监听事件
					this.getVideoGroupUserfun();  // 获取当前房间人物信息
				}
			},1000)
		},
		methods: {
			isdevicefun(){
				const detect = new RTCDetect();
				let Supported = detect.getAPISupported();
				if (Supported.isWebRTCSupported) { // 支持webRTC
					detect.getDevicesAsync().then((res) => {
						if (res.hasMicrophonePermission && res.microphones.length > 0) {
							if (res.speakers.length > 0) {
								this.isdevice = true;
							}
						}
					})
				}
			},
			answerfun(data){
				let extendsdata = data;
				this.msgid = extendsdata.msg_id;
				this.chat_sign = extendsdata.chat_sign;
				// console.log(extendsdata.type+'--'+extendsdata.from_user.user_id +'---'+this.userInfo.user_id)
				if (extendsdata.type == 'calling') { //  呼叫中（state：1=显示挂断，2=对方拨打；打开接听按钮）
					if(extendsdata.from_user.user_id == this.userInfo.user_id){
						this.state = 1;
					}else{
						this.state = 2;
					}
				};
				if (extendsdata.type == 'accept') { // 通话
					this.state = 2;
					this.getVideoGroupUserfun();
				};
				/* call_status : 0空闲  1呼叫中 2通话中 3通话结束 4通话取消
									0：不是语音通话
									1：有人拨打语音
									2：至少有一个人接听语音
									3：所有人离开房间 语音结束
									4：无人接听 拨打者取消 */ 
				if (extendsdata.call_status == 3 || extendsdata.call_status == 4) {  //  无人进入  拨打者自己挂断
					this.exitRoomfun()
				};
				if (extendsdata.type == 'refuse_all') { //  呼叫中
					this.state = 4;
					this.client.exitRoom();
					if(this.isdevice){
						this.client.stopLocalAudio(); // 正式打开
					}
					this.electron.ipcRenderer.send("childClose");
					if(this.isdevice){
						if (this.$refs.audioplay) {  // 正式打开
							this.$refs.audioplay.pause();
						}
					}
				};
				this.getVideoGroupUserfun();
			},
			initClient(goroom) { // 初始化-获取UserSign
				this.apifun.$post('/pc/im/getUserSign', {}).then((res) => {
					if (res.code == 200) {
						let datas = res.data;
						this.userSig = datas;
						let tetcdata = {
							mode: 'rtc',
							sdkAppId: this.sdkAppId,
							userId: this.userId,
							userSig: datas,
						};
						this.client = TRTC.create(tetcdata);
						this.startLocalAudio() // 正式打开
						if(goroom == 'room'){
							this.enterRoomfun();
						};
						this.handleClientEvents();
					}
				})
			},
			enterRoomfun() { // 进房
				let enterRoom = {
					strRoomId: this.msgid.toString(),
					sdkAppId: this.sdkAppId,
					userId: this.userId,
					userSig: this.userSig,
					autoReceiveAudio: true
				}
				this.client.enterRoom(enterRoom);
			},
			exitRoomfun() { // 退出房间
				this.state = 4;
				let sendData = {
					msg_id :this.msgid
					// code: code,  // 901语音通话 902已取消通话 903已拒绝 905未接通 906通话时长callTime 907忙线中 908其他端已操作
				};
				let urls='/group/chatVoice/hangup'   //挂断
				if(this.state == 2){
					urls = '/group/chatVoice/refuse';  // 拒接
				};
				this.apifun.$post(urls, sendData).then((res) => {
					// console.log('挂断',res)
					this.client.exitRoom();
					if (res.code == 200) {
						let datas = res.data;
						this.msgid = '';
						this.electron.ipcRenderer.send("chatsend",datas)  // 将datas数据返回到聊天页面
						// 关闭win窗
						this.client.stopLocalAudio();
						this.electron.ipcRenderer.send("childClose");
						if (this.$refs.audioplay) {
							this.$refs.audioplay.pause();
						}
					};
				});
			},
			callfun() { // 拨打
				let sendData = {
					chat_sign:this.chat_sign
				}
				this.state = 1;
				this.apifun.$post('/group/chatVoice/call', sendData).then((res) => {
					// console.log(res)
					if (res.code == 200) {
						let datas = res.data;
						this.msgid = datas;
						if(!this.userSig){
							this.initClient('room');   // 初始化房间-进入房间、监听事件
						}else{
							this.enterRoomfun();
						}
						this.getVideoGroupUserfun();  // 获取当前房间人物信息
						// if(datas.extends.code == 907){  // 忙线
						// 	this.electron.ipcRenderer.send("childClose");
						// 	this.client.exitRoom();
						// }
					}
				})
			},
			sendcalljtfun() { // 接听
				let sendData = {
					msg_id: this.msgid,
				}
				this.state = 3;
				this.apifun.$post('/group/chatVoice/accept', sendData).then((res) => {
					if (res.code == 200) {
						if(!this.userSig){
							this.initClient('room');   // 初始化房间-进入房间、监听事件
						}else{
							this.enterRoomfun();
						}
						this.getVideoGroupUserfun();  // 获取当前房间人物信息
						if (!this.$refs.audioplay.paused) {
							this.$refs.audioplay.pause();
						}
					}
				})
			},
			getVideoGroupUserfun(){ // 获取当前房间人物信息
				this.apifun.$post('/group/chatVoice/getVideoGroupUser', {
					chat_sign:this.chat_sign
				}).then((res) => {
					if (res.code == 200) {
						let datas = res.data;
						this.groupUserData = datas.chat_user || [];
						
						this.groupUserData.forEach((item,index)=>{  // 当列表中有自己；才算接通；否则为等待接通
							if(item.user_id == this.userInfo.user_id){
								this.state = 3;
							}
						});
						if(this.isdevice){
							if(this.state == 3){ // 正式打开
								this.startLocalAudio();   
								if (!this.$refs.audioplay.paused) {
									this.$refs.audioplay.pause();
								}
							}
						}
						if(this.groupUserData.length <= 1 && this.state > 2){
							this.state = 4;
							// this.exitRoomfun();
							this.client.exitRoom();  // 正式打开
							if(this.isdevice){
								this.client.stopLocalAudio(); // 正式打开
							}
							this.msgid = '';
							this.electron.ipcRenderer.send("childClose");
						}
					}
				})
			},
			async startLocalAudio() {
				this.client.enableAudioVolumeEvaluation(500);
				this.client.setRemoteAudioVolume('*',100);
				this.client.startLocalAudio();
				this.client.updateLocalAudio({ mute: false });
			},
			handleClientEvents() { // 监听事件
				let that = this;
				this.client.on('error', (error) => {
					console.error('on-error--', error);
				});
				this.client.on('connection-state-changed', (
				event) => { //  'DISCONNECTED'：连接断开		'CONNECTING'：正在连接中		'CONNECTED'：已连接
					const prevState = event.prevState;
					const curState = event.state;
					if (prevState == 'CONNECTING' && curState == "DISCONNECTED") { // 失败
						this.exitRoomfun()
					}
					if (prevState == 'CONNECTED' && curState == "DISCONNECTED") { // 失败
						this.exitRoomfun()
					}
				});
				this.client.on('remote-user-enter', (event) => { // 远端用户进房事件
					console.log('用户进房',event.userId)
					this.startLocalAudio();  // 正式打开
					this.getVideoGroupUserfun();  // 获取房间人数
				});
				this.client.on('remote-user-exit', (event) => { // 远端用户退房事件
					console.log('用户退房',event.userId)
					this.getVideoGroupUserfun();  // 获取房间人数
				});
			
				this.client.on('remote-audio-available', (event) => { 
					console.error('远端用户发布音频--', event);  // event.userId
					// that.state = 3;
					this.startLocalAudio();  // 正式打开
					// this.$refs.audioplay.pause();
				});
				this.client.on('remote-audio-unavailable', (event) => {
					console.error('远端用户关闭音频--', event);   // event.userId
					// that.state = 4;
					// this.exitRoomfun();
					// this.electron.ipcRenderer.send("childClose");
				});
				/*相关事件
				被踢出房间:kicked-out、远端用户进房事件：remote-user-enter 、远端用户退房事件：remote-user-exit
				音量大小事件：audio-volume
				*/
			},
			colsed() {  // 关闭
				this.exitRoomfun();
				setTimeout(()=>{
					this.electron.ipcRenderer.send("childClose");
				},5000)
			},
			mini() {  // 缩小
				this.electron.ipcRenderer.send("child-mini");
			},
			async getMicrophoneList() { // 检测麦克风设备列表
				const microphoneList = await TRTC.getMicrophoneList();
				if (microphoneList[0] && microphoneList[0].getCapabilities) {
					const {
						channelCount
					} = microphoneList[0].getCapabilities();
					this.microphonenum = channelCount.max
				}
			},
			async isSupported() { // 检测浏览器是否支持TRTC
				TRTC.isSupported().then((checkResult) => {
					if (!checkResult.result) {
						console.log('checkResult', checkResult.result, 'checkDetail', checkResult.detail);
						// SDK 不支持当前浏览器，引导用户使用最新版的 Chrome 浏览器。
						this.iszcTRTC = false
					} else {
						this.iszcTRTC = true
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.topcontrol {
		position: fixed;
		top: 0;
		z-index:99;
		-webkit-app-region: drag;
		width: 100%;
		height: 30px;
		background-color: #fff;
		padding-bottom:10px;
		border-bottom: 1px solid #cccccc;
		.topcontrolr {
			-webkit-app-region: no-drag;
			// width: 100px;
			width: 50px;
			height: 30px;
			padding-top: 10px;
			position: absolute;
			right: 10px;
			top: 0px;
			justify-content: flex-end;

			.topcontrolreach {
				width: 30px;
				height: 30px;
				line-height: 30px;
				margin-left: 10px;
				line-height: 30px;
				font-size: 20px;
				text-align: center;
				border-radius:10px;
			}
			.topcontrolreach :hover{
				background-color: var(--mainColor);
				color: #fff;
			}
		}
	}
	// 内容
	.voicemain {
		position: relative;
		top:50px;
		width: 340px;
		height: 550px;
		background-color: #fff;
	}
	
	.voicemain-head {
		width: 100%;
	
		.voicemain-headavater {
			width:210px;
			height:210px;
			margin: auto;
			display: flex;
			flex-wrap: wrap;
			overflow-y:auto;
			.headavatereach{
				width: 70px;
				height:70px;
				margin: auto;
				text-align: center;
				.headavatereachtitle{
					width: 70px;
					font-size:14px;
					color: #333;
					line-height: 20px;
					text-align: center;
				}
				img {
					display: inline-block;
					width: 50px;
					height:50px;
					margin: auto;
				}
			}
			
		}
	
		.voicemain-headname {
			line-height: 40px;
			font-size: 14px;
			text-align: center;
			color: #333;
		}
	}
	
	.voicemain-bottonbtn {
		position: absolute;
		width: 100%;
		bottom: 40px;
		z-index: 0;
	
		.voicemain-btnequipment {
			width: 70%;
			text-align: center;
			padding: 10px;
			background-color: #F4F4F4;
			border-radius: 8px;
			color: #333;
			font-size: 14px;
			line-height: 20px;
			margin: 0 auto 20px;
		}
	
		.voicemain-bottonbtnmain {
			width: 90%;
			justify-content: space-around;
	
			.voicemain-bottonbtneach {
				width: 50px;
				height: 50px;
				border-radius: 50%;
			}
		}
	
	}
</style>